package com.bruce.commonutils;

import android.util.Log;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import retrofit.client.OkClient;

import java.io.IOException;

/**
 * Created by wangzhijie@wind-mobi.com on 2015/9/1.
 */
public class RetrofitUtils {
    public static OkClient newClient(final int retryCount) {
        OkHttpClient client = new OkHttpClient();
        client.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                // try the request
                Response response = chain.proceed(request);
                int tryCount = 0;
                while (!response.isSuccessful() && tryCount < retryCount) {
                    Log.d("intercept", "Request is not successful - " + tryCount);
                    tryCount++;
                    // retry the request
                    response = chain.proceed(request);
                }
                // otherwise just pass the original response on
                return response;
            }
        });
        return new OkClient(client);
    }
}
